<?php

namespace Admin\Controller;

use Common\Common\AdminController;
use Common\Top;
use Common\Utils;

class ProviderController extends AdminController
{


    public function index()
    {
        $name = trim(I('names'));
        $operatorId = session('operator_id');
        $state = Top::StateDeleted;
        $roleId = session('role_id');

        $this->operatorData = C('SHOW_OPERATOR_DATA');

        if (strpos($this->operatorData, $roleId) !== false) {
            $this->operatorList = M('operator')->where('id != 2')->field('id,display_name')->select();
            $this->oid = !empty(I('get.oid')) ? I('get.oid') : 0;
            $operatorId = $this->oid;

            if ($this->oid == 0) {
                $operatorId = implode(',', array_column($this->operatorList, 'id'));
            }
        }

        if ($name) {
            $where = "operator_id in($operatorId) && state != '{$state}' && (name like '%%$name%%' or full_name like '%%$name%%')";
        } else {
            $where = "operator_id in($operatorId) && state != '{$state}'";
        }


        $list = Utils::pages('provider', $where, C('PAGE_SET'), $order = " id desc ");
        $this->assign('name', $name);
        $this->info = $list['info'];
        $this->page = $list['page'];
        $this->oper = M('operator')->field('id,name')->find(session('entity_id'));
        $this->display();
    }


    /**
     * 设置账号状态 - 禁用 冻结
     */
    public function setAccountStatus()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $state = I('state');
            $id = I('id', 0, 'int');

            $info = M('provider')->where("id = '{$id}'")->find();

            if ($state && $id) {
                $entityType = Top::EntityTypeProvider;
                $logData['operator_id'] = $info['operator_id'];
                $logData['user_id'] = session('user_id');
                $logData['user_name'] = session('entity_name');
                $logData['action'] = $logData['user_name'] . "禁用了供应商" . $info['name'] . "的账号";
                $logData['memo'] = I('memo');
                $logData['create_time'] = date("Y-m-d H:i:s", time());

                if ($state == Top::StateEnabled || $state == Top::StateDisabled) {
                    if ($state == Top::StateEnabled) {
                        $logData['action'] = $logData['user_name'] . "恢复了供应商" . $info['name'] . "的账号状态";
                    }

                    M('log_account_status')->add($logData);

                    if ($state == $info['state']) {
                        $data['status'] = 1;
                        $this->ajaxReturn($data);
                    }

                    $result = M('provider')->where("id = '{$id}'")->setField('state', $state);
                    M('user')->where("entity_id = '{$id}' && entity_type = '{$entityType}'")->setField('state', $state);
                } elseif ($state == 'freeze2' || $state == 'nofreeze1') {
                    if ($state == 'freeze2') {
                        $account_state = Top::StateDisabled;
                        $logData['action'] = $logData['user_name'] . "冻结了供应商" . $info['name'] . "的账户";
                    } elseif ($state == 'nofreeze1') {
                        $account_state = Top::StateEnabled;
                        $logData['action'] = $logData['user_name'] . "恢复了供应商" . $info['name'] . "的账户状态";
                    }

                    M('log_account_status')->add($logData);

                    if ($state == $info['account_state']) {
                        $data['status'] = 1;
                        $this->ajaxReturn($data);
                    }

                    $result = M('provider')->where("id = '{$id}'")->setField('account_state', $account_state);
                }

                if ($result) {
                    $data['status'] = 1;
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '不能重复提交';
                    $this->ajaxReturn($data);
                }
            } else {
                return false;
            }
        }
    }


    /**
     * 查看供应商代码
     */
    public function showProviderCode()
    {
        if (IS_POST && IS_AJAX) {
            $where['id'] = I('id');
            $info = M('provider')->where($where)->field('id,code')->find();

            if ($info) {
                $data['status'] = 1;
                $data['code'] = $info['code'];
                $this->ajaxReturn($data);
            }
        }
    }


    /**
     * 添加供应商财务代码
     */
    public function addProviderCode()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $where['id'] = I('id');
            $data['code'] = I('code');

            $info = M('provider')->where($where)->find();

            $code = $info['code'];

            if ($code == $data['code']) {
                $data['status'] = 1;
                $data['msg'] = '操作成功';
                $this->ajaxReturn($data);
            }

            $result = M('provider')->where($where)->save($data);

            if ($result) {
                $data['status'] = 1;
                $data['msg'] = '操作成功';
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }
        }
    }


    /**
     * 查看账户金额信息
     */
    public function showProviderAccountInfo()
    {
        if (IS_POST && IS_AJAX) {
            $id = I('id');
            $providerInfo = M('provider')->where("id = '{$id}'")->field('id,name,account_balance')->find();
            $entityType = Top::EntityTypeProvider;
            $operatorId = session('operator_id');
            $providerId = $providerInfo['id'];
            $roleId = session('role_id');

            $providerAccountInfo = M('provider_account')->where("provider_id = '{$providerId}' && operator_id = '{$operatorId}'")->find();

            $this->operatorData = C('SHOW_OPERATOR_DATA');
            if (strpos($this->operatorData, $roleId) !== false) {
                $providerAccountInfo = $providerInfo;
            }

            if ($providerAccountInfo) {
                $data['status'] = 1;
                $total = $providerAccountInfo['account_balance'];
                $frozenMoney = Utils::getProviderInOperatorFrozenFen($entityType, $id, $operatorId);
                $data['name'] = $providerAccountInfo['provider_name'];

                if (strpos($this->operatorData, $roleId) !== false) {
                    $data['name'] = $providerInfo['name'];
                    $frozenMoney = Utils::getProviderAllFrozenFen($entityType, $id);
                }

                $data['total'] = Utils::getYuan($total);
                $data['frozenMoney'] = Utils::getYuan($frozenMoney);
                $data['availableBalance'] = Utils::getYuan($total - $frozenMoney);
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 1;
                $data['name'] = $providerInfo['name'];
                $data['total'] = '0.00';
                $data['frozenMoney'] = '0.00';
                $data['availableBalance'] = '0.00';
                $this->ajaxReturn($data);
            }
        }
    }


    /**
     * 查看交易记录
     */
    public function showTransaction()
    {
        if ($this->warnStatus == '10404') {
            $this->redirect("Error/index");
        }

        $entity_type = Top::EntityTypeProvider;
        $entity_id = I('get.aid');
        $operatorId = I('get.oid');
        $action = trim(I('entity_name'));
        $startTime = !empty(I('start_time')) ? I('start_time') : date("2015-05-01", time());
        $endTime = !empty(I('end_time')) ? I('end_time') : date('Y-m-d', time());

        $where = "operator_id = '{$operatorId}' && entity_type = '{$entity_type}' && entity_id = '{$entity_id}' && action like '%%$action%%' && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
        $pageInfo = Utils::pages('account_transaction', $where, C('TRANSACTION_PAGE_SET'), $order = " id desc ");

        foreach ($pageInfo['info'] as $key => $vo) {
            if ($vo['object_type'] == 5) {
                $pageInfo['info'][$key]['objectName'] = M('order_tour')->where("id = " . $vo['object_id'])->field('tour_name')->find();
            } else if ($vo['object_type'] == 6) {
                $pageInfo['info'][$key]['objectName'] = M('order_product')->where("id = " . $vo['object_id'])->field('product_name tour_name')->find();
            } else if ($vo['object_type'] == 2) {
                $pageInfo['info'][$key]['objectName']['tour_name'] = '提现';
            } else if ($vo['object_type'] == 8) {
                $pageInfo['info'][$key]['objectName']['tour_name'] = '账户调整';
            }
        }

        $total = M('account_transaction')->where($where)->field('count(id) totalNum, sum(amount) totalPrice')->select();

        $saction['action'] = '支出线路产品订单佣金';
        $commissionTotal = M('account_transaction')->where($where)->where($saction)->field('sum(amount) commissionTotal')->select();

        $agencyInfo = M('provider')->where("id = '$entity_id'")->find();
        $name = $agencyInfo['name'];

        $this->info = $pageInfo['info'];
        $this->page = $pageInfo['page'];
        $this->assign('name', $name);
        $this->assign('sname', $action);
        $this->assign('startTime', $startTime);
        $this->assign('endTime', $endTime);
        $this->assign('total', $total);
        $this->assign('commissionTotal', $commissionTotal);

        $this->display();
    }


    public function add()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $login_name = I('login_name');
            $info = M('user')->where("login_name = '{$login_name}'")->find();
            $login_pwd = I('login_pwd');
            $login_pwd2 = I('login_pwd2');

            if ($login_pwd != $login_pwd2) {
                $data['status'] = 0;
                $data['msg'] = '两次密码不一致';
                $this->ajaxReturn($data);
            }

            if ($info) {
                $data['status'] = 0;
                $data['msg'] = '该供应商信息已存在，不可用';
                $this->ajaxReturn($data);
            } else {
                M('provider')->startTrans();
                try {
                    $data['account_state'] = Top::StateEnabled;
                    $data['operator_id'] = I('opname');
                    $data['name'] = I('name');
                    $data['full_name'] = I('full_name');
                    $data['destinations'] = str_replace("，", ",", I('destinations'));
                    $data['account'] = Utils::getNextAccount(Top::EntityTypeProvider, $data['operator_id']);
                    $data['commission_rate'] = Utils::SetCommission(I('commission_rate'));
                    $data['create_time'] = date("Y-m-d H:i:s", time());
                    $data['state'] = Top::StateEnabled;

                    $result = M('provider')->add($data);

                    $user_data['is_admin'] = 1;
                    $user_data['role_id'] = Top::DefalutProviderRoleId;
                    $user_data['entity_type'] = Top::EntityTypeProvider;
                    $user_data['entity_id'] = $result;
                    $user_data['login_name'] = $login_name;
                    $user_data['login_pwd'] = Utils::getHashPwd($login_pwd);
                    $user_data['name'] = I('name');
                    $user_data['state'] = Top::StateEnabled;
                    $user_data['create_time'] = date("Y-m-d H:i:s", time());

                    $userResult = M('user')->add($user_data);

                    if ($result && $userResult) {
                        M('provider')->commit();
                        $data['status'] = 1;
                        $data['msg'] = '操作成功';
                        $this->ajaxReturn($data);
                    } else {
                        $data['status'] = 0;
                        $data['msg'] = '操作失败';
                        $this->ajaxReturn($data);
                    }
                } catch (Exception $ex) {
                    M('provider')->rollback();
                }
            }
        }
    }


    public function editProviderPwd()
    {
        if (IS_AJAX && IS_POST) {
            $id = I('id');
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '修改失败';
                $this->ajaxReturn($data);
            }

            $user['entity_id'] = $id;
            $user['entity_type'] = Top::EntityTypeProvider;

            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $pwd = I('newpwd');
            $pwd = Utils::getHashPwd($pwd);
            $confirm_password = I('password2');
            $confirm_password = Utils::getHashPwd($confirm_password);

            if ($pwd != $confirm_password) {
                $data['status'] = 3;
                $data['msg'] = '两次密码不一致';
                $this->ajaxReturn($data);
            } else {
                $data['login_pwd'] = $pwd;
                $data['update_time'] = date("Y-m-d H:i:s", time());
                M('user')->where($user)->save($data);
                $data['status'] = 1;
                $data['msg'] = '修改成功';
                $this->ajaxReturn($data);
            }
        }
    }


    public function edit()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $id = I('id', 0, 'int');
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '编辑失败';
                $this->ajaxReturn($data);
            }

            $login_name = I('login_name');
            $info = M('user')->where("entity_id != '{$id}' && login_name = '{$login_name}'")->find();

            if ($info) {
                $data['status'] = 0;
                $data['msg'] = '该供应商信息已存在，不可用';
                $this->ajaxReturn($data);
            } else {
                $data['name'] = I('name');
                $data['contact_person'] = I('contact_person');
                $data['mobile'] = I('mobile');
                $data['destinations'] = str_replace("，", ",", I('destinations'));
                $data['commission_rate'] = Utils::SetCommission(I('commission_rate'));
                $data['contract_start_time'] = !empty(I('timestart')) ? I('timestart') : '0000-00-00 00:00:00';
                $data['contract_end_time'] = !empty(I('timeend')) ? I('timeend') : '0000-00-00 00:00:00';
                $data['bank_name'] = I('bank_name');
                $data['bank_account'] = I('bank_account');
                $data['phone'] = trim(I('phone'));
                $data['settlement_interval'] = I('settlement_interval');
                $data['update_time'] = date("Y-m-d H:i:s", time());

                $result = M('provider')->where("id = '{$id}'")->save($data);

                $where['is_admin'] = 1;
                $where['role_id'] = Top::DefalutProviderRoleId;
                $where['entity_type'] = Top::EntityTypeProvider;
                $where['entity_id'] = $id;

                $productMessage = I('productMessage');
                $transactionMessage = I('transactionMessage');
                $user_data['login_name'] = I('login_name');
                $user_data['name'] = I('name');
                $user_data['mobile'] = I('mobile');
                $user_data['notify_msg_types'] = "," . $productMessage . "," . $transactionMessage . ",";
                $user_data['update_time'] = date("Y-m-d H:i:s", time());

                $userResult = M('user')->where($where)->save($user_data);

                if ($result && $userResult) {
                    $data['status'] = 1;
                    $data['msg'] = '编辑成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '编辑失败';
                    $this->ajaxReturn($data);
                }
            }
        } else {
            $id = I('aid', 0, 'int');
            $providerInfo = M('provider')->where("id='{$id}'")->find();
            $providerInfo['commission_rate'] = Utils::GetCommissionRate($providerInfo['commission_rate']);
            //查找user表
            $data['entity_id'] = $providerInfo['id'];
            $data['entity_type'] = Top::EntityTypeProvider;
            $data['role_id'] = Top::DefalutProviderRoleId;
            $data['is_admin'] = 1;
            $userInfo = M('user')->where($data)->find();
            $notifyMsgTypes = explode(",", $userInfo['notify_msg_types']);
            array_shift($notifyMsgTypes);
            array_pop($notifyMsgTypes);
            $productMessage = $notifyMsgTypes[0];
            $transactionMessage = $notifyMsgTypes[1];

            $this->assign('productMessage', $productMessage);
            $this->assign('transactionMessage', $transactionMessage);
            $this->assign('list', $providerInfo);
            $this->assign('user_list', $userInfo);
        }
        $this->display();
    }


    public function seniorEdit()
    {
        if ($this->warnStatus == '10404') {
            $data['status'] = 2;
            $data['msg'] = $this->warnInfo;
            $this->ajaxreturn($data);
        }

        $id = I('id');
        $keyid = Utils::getDecrypt(I('keyid'));

        if ($id != $keyid) {
            $data['status'] = 0;
            $data['msg'] = '操作失败';
            $this->ajaxReturn($data);
        }

        $data['full_name'] = I('full_name');

        $result = M('provider')->where("id = '{$id}'")->save($data);

        if ($result) {
            $data['status'] = 1;
            $data['msg'] = '操作成功';
            $this->ajaxReturn($data);
        } else {
            $data['status'] = 0;
            $data['msg'] = '操作失败';
            $this->ajaxReturn($data);
        }
    }


    public function delete()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $ids = I('action_code');
            $operatorId = session('operator_id');
            $entityType = Top::EntityTypeProvider;
            $data['state'] = Top::StateDeleted;

            M('provider')->startTrans();
            try {
                foreach ($ids as $id) {
                    $id = Utils::getDecrypt($id);
                    $result = M('provider')->where("id = '{$id}' && operator_id = '{$operatorId}'")->save($data);
                    $userResult = M('user')->where("entity_id = '{$id}' && entity_type = '{$entityType}'")->save($data);
                }

                if ($result && $userResult) {
                    M('provider')->commit();
                    $data['status'] = 1;
                    $data['msg'] = '删除成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '删除失败';
                    $this->ajaxReturn($data);
                }
            } catch (Exception $ex) {
                M('provider')->rollback();
            }
        } else {
            $data['status'] = 2;
            $data['msg'] = '系统出错';
            $this->ajaxReturn($data);
        }
    }


    /**
     * 审核线路产品操作及列表
     */
    public function auditTourProduct()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $where['id'] = I('id');
            $data['audit_memo'] = I('memo');
            $data['state'] = I('state', 0, 'int');
            $info = M('tour')->where($where)->field('id,name,user_id,state')->find();
            $userId = $info['user_id'];

            if ($data['state'] == Top::ProductStateIsSale && $info['state'] == Top::ProductStateIsSale) {
                $data['status'] = 2;
                $data['msg'] = '该产品已经审核';
                $this->ajaxReturn($data);
            } else if ($data['state'] == Top::ProductStateIsSale && $info['state'] == Top::ProductStateCanceled) {
                $data['status'] = 3;
                $data['msg'] = '该产品已经下架';
                $this->ajaxReturn($data);
            } else if ($data['state'] == Top::ProductStateIsSale && $info['state'] == Top::ProductStateRejected) {
                $data['status'] = 4;
                $data['msg'] = '该产品已经拒绝';
                $this->ajaxReturn($data);
            } else if ($data['state'] == Top::ProductStateIsSale && $info['state'] == Top::ProductStateNotSubmitted) {
                $data['status'] = 5;
                $data['msg'] = '该产品还没有提交';
                $this->ajaxReturn($data);
            } else if ($data['state'] == Top::ProductStateRejected && $info['state'] == Top::ProductStateNotSubmitted) {
                $data['status'] = 6;
                $data['msg'] = '该产品还没有提交';
                $this->ajaxReturn($data);
            } else if ($data['state'] == Top::ProductStateRejected && $info['state'] == Top::ProductStateRejected) {
                $data['status'] = 7;
                $data['msg'] = '该产品已经拒绝';
                $this->ajaxReturn($data);
            } else if ($data['state'] == Top::ProductStateRejected && $info['state'] == Top::ProductStateIsSale) {
                $data['status'] = 8;
                $data['msg'] = '该产品已经审核，不能拒绝';
                $this->ajaxReturn($data);
            } else {
                $result = M('tour')->where($where)->save($data);

                if ($data['state'] == Top::ProductStateRejected) {
                    $userInfo = $this->getUserInfo($userId);

                    if ($this->getTransactionMessageType($userInfo)) {
                        $toUser = $userInfo['weixinmp_openid'];
                        $templateId = Utils::productCheckResultTemplateId();
                        $content = "您好, 您的产品: 10" . $info['id'] . $info['name'] . " 未通过上架申请";
                        $type = "上架申请";
                        $remark = "拒绝理由: " . $data['audit_memo'];
                        $this->send($toUser, $templateId, $content, $type, $remark);
                    }
                }

                if ($result) {
                    $data['status'] = 1;
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '系统出错啦';
                    $this->ajaxReturn($data);
                }
            }
        } else {
            $name = trim(I('name'));
            $operator_id = session('operator_id');
            $state = I('state');
            $nameCode = substr($name, 0, 2);

            if ($nameCode == 10) {
                $code = substr($name, 2);
            }

            $roleId = session('role_id');

            $this->operatorData = C('SHOW_OPERATOR_DATA');

            if (strpos($this->operatorData, $roleId) !== false) {
                $this->operatorList = M('operator')->where('id != 2')->field('id,display_name')->select();
                $this->oid = !empty(I('get.oid')) ? I('get.oid') : 0;
                $operator_id = $this->oid;

                if ($this->oid == 0) {
                    $operator_id = implode(',', array_column($this->operatorList, 'id'));
                }
            }

            if (!empty($name)) {

                if ($state == '2' || $state == '3' || $state == '4' || $state == '5') {
                    $where = "(name like '%$name%' or id = '{$code}' or provider_name like '%$name%' or destination like '%$name%') and operator_id = '{$operator_id}' and state != 1 and state = '{$state}'";
                    $record_sum = M('tour')->where($where)->count();
                    $info = Utils::pages('tour', $where, 20, $order = " id desc ");
                } else if ($state == '6') {
                    $where = "(name like '%$name%' or id = '{$code}'  or provider_name like '%$name%' or destination like '%$name%') and operator_id = '{$operator_id}' and is_top = 1";
                    $record_sum = M('tour')->where($where)->count();
                    $info = Utils::pages('tour', $where, 20, $order = " id desc ");
                }
//                else if ($state == '7') {
//                    $where = "(name like '%$name%' or id = '{$code}'  or provider_name like '%$name%' or destination like '%$name%') and operator_id = '{$operator_id}' and is_marquee = 1";
//                    $record_sum = M('tour')->where($where)->count();
//                    $info = Utils::pages('tour', $where, 20, $order = " id desc ");
//                } 
                else {
                    $where = "(name like '%$name%' or id = '{$code}'  or provider_name like '%$name%' or destination like '%$name%') and operator_id = '{$operator_id}' and state != 1";
                    $record_sum = M('tour')->where($where)->count();
                    $info = Utils::pages('tour', $where, 20, $order = " id desc ");
                }
            } else {
                if ($state == '2' || $state == '3' || $state == '4' || $state == '5') {
                    $where = "operator_id = '{$operator_id}' and state != 1 and state = '{$state}'";
                    $record_sum = M('tour')->where($where)->count();
                    $info = Utils::pages('tour', $where, 20, $order = " id desc ");
                } else if ($state == '6') {
                    $where = "operator_id = '{$operator_id}' and is_top = 1";
                    $record_sum = M('tour')->where($where)->count();
                    $info = Utils::pages('tour', $where, 20, $order = " id desc ");
                } else if ($state == '7') {
                    $where = "operator_id = '{$operator_id}' and is_marquee = 1";
                    $record_sum = M('tour')->where($where)->count();
                    $info = Utils::pages('tour', $where, 20, $order = " update_time desc ");
                } else {
                    $where = "operator_id = '{$operator_id}' and state != 1";
                    $record_sum = M('tour')->where($where)->count();
                    $info = Utils::pages('tour', $where, 20, $order = " id desc ");
                }
            }

            $nowDate = strtotime(date('Y-m-d 00:00:00', time()));

            foreach ($info['info'] as $k => $v) {
                $arr[$k] = array(
                    'latest_sku1' => strtotime(date('Y-m-d 00:00:00', strtotime('-2 day', strtotime($v['latest_sku'])))),
                    'id' => $v['id'],
                    'name' => $v['name'],
                    'provider_name' => $v['provider_name'],
                    'departure' => $v['departure'],
                    'destination' => $v['destination'],
                    'state' => $v['state'],
                    'create_time' => $v['create_time'],
                    'update_time' => $v['update_time'],
                    'latest_sku' => $v['latest_sku'],
                    'is_top' => $v['is_top'],
                    'promotion' => $v['promotion'],
//                    'is_marquee' => $v['is_marquee'],
                    'provider_type' => $v['provider_type'],
                    'audit_memo' => $v['audit_memo'],
                    'min_price' => $v['min_price'],
                );
            }

            $this->assign('name', $name);
            $this->assign('nowDate', $nowDate);
            $this->state = $state;
            $this->total = $record_sum;
            $this->info = $arr;
            $this->page = $info['page'];
        }

        $this->display();
    }


    /**
     * 通用产品 - 显示佣金比例
     */
    function showGeneralProductCommission()
    {
        if (IS_POST && IS_AJAX) {
            $where['id'] = I('id');
            $info = M('product')->where($where)->find();

            if ($info) {
                $data['commission_rate'] = Utils::GetCommissionRate($info['commission_rate']);
                $this->ajaxReturn($data);
            }
        }
    }


    /**
     * 通用产品 - 佣金比例设置
     */
    function saveGeneralProductCommission()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            $data['commission_rate'] = Utils::SetCommission(I('commission_rate'));
            $result = M('product')->where($where)->save($data);

            if ($result) {
                $data['status'] = 1;
                $data['msg'] = '操作成功';
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }
        }
    }


    /**
     *审核通用产品操作及列表
     */
    public function auditGeneralProduct()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $where['id'] = I('id');
            $data['audit_memo'] = I('memo');
            $data['state'] = I('state', 0, 'int');
            $info = M('product')->where($where)->field('state')->find();

            if ($data['state'] == Top::ProductStateIsSale && $info['state'] == Top::ProductStateIsSale) {
                $data['status'] = 2;
                $data['msg'] = '该产品已经审核';
                $this->ajaxReturn($data);
            } else if ($data['state'] == Top::ProductStateIsSale && $info['state'] == Top::ProductStateCanceled) {
                $data['status'] = 3;
                $data['msg'] = '该产品已经下架';
                $this->ajaxReturn($data);
            } else if ($data['state'] == Top::ProductStateIsSale && $info['state'] == Top::ProductStateRejected) {
                $data['status'] = 4;
                $data['msg'] = '该产品已经拒绝';
                $this->ajaxReturn($data);
            } else if ($data['state'] == Top::ProductStateIsSale && $info['state'] == Top::ProductStateNotSubmitted) {
                $data['status'] = 5;
                $data['msg'] = '该产品还没有提交';
                $this->ajaxReturn($data);
            } else if ($data['state'] == Top::ProductStateRejected && $info['state'] == Top::ProductStateNotSubmitted) {
                $data['status'] = 6;
                $data['msg'] = '该产品还没有提交';
                $this->ajaxReturn($data);
            } else if ($data['state'] == Top::ProductStateRejected && $info['state'] == Top::ProductStateRejected) {
                $data['status'] = 7;
                $data['msg'] = '该产品已经拒绝';
                $this->ajaxReturn($data);
            } else if ($data['state'] == Top::ProductStateRejected && $info['state'] == Top::ProductStateIsSale) {
                $data['status'] = 8;
                $data['msg'] = '该产品已经审核，不能拒绝';
                $this->ajaxReturn($data);
            } else {
                $result = M('product')->where($where)->save($data);
                if ($result) {
                    $data['status'] = 1;
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '系统出错啦';
                    $this->ajaxReturn($data);
                }
            }
        } else {
            $name = trim(I('name'));
            $operator_id = session('operator_id');
            $state = I('state');
            $roleId = session('role_id');

            $this->operatorData = C('SHOW_OPERATOR_DATA');

            if (strpos($this->operatorData, $roleId) !== false) {
                $this->operatorList = M('operator')->where('id != 2')->field('id,display_name')->select();
                $this->oid = !empty(I('get.oid')) ? I('get.oid') : 0;
                $operator_id = $this->oid;

                if ($this->oid == 0) {
                    $operator_id = implode(',', array_column($this->operatorList, 'id'));
                }
            }

            if (!empty($name)) {

                if ($state != 0) {
                    $where = "(name like '%$name%' or user_name like '%$name%') and operator_id = '{$operator_id}' and state != 1 and state = '{$state}'";
                    $record_sum = M('product')->where($where)->count();
                    $info = Utils::pages('product', $where, 20, $order = " create_time desc ");
                } else {
                    $where = "(name like '%$name%' or user_name like '%$name%') and operator_id = '{$operator_id}' and state != 1";
                    $record_sum = M('product')->where($where)->count();
                    $info = Utils::pages('product', $where, 20, $order = " create_time desc ");
                }
            } else {
                if ($state != 0) {
                    $where = "operator_id = '{$operator_id}' and state != 1 and state = '{$state}'";
                    $record_sum = M('product')->where($where)->count();
                    $info = Utils::pages('product', $where, 20, $order = " create_time desc ");
                } else {
                    $where = "operator_id = '{$operator_id}' and state != 1";
                    $record_sum = M('product')->where($where)->count();
                    $info = Utils::pages('product', $where, 20, $order = " create_time desc ");
                }
            }


            $this->state = $state;
            $this->total = $record_sum;
            $this->assign('name', $name);
            $this->info = $info['info'];
            $this->page = $info['page'];
            $this->display();
        }
    }


    /**
     * 置顶操作
     */
    public function topRecommended()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            $tourInfo = M('tour')->where($where)->field('id,user_id,name,is_top,state')->find();
            $userId = $tourInfo['user_id'];
            $isTopState = $tourInfo['is_top'];
            $state = $tourInfo['state'];
            $tourState = Top::ProductStateIsSale;

            if ($isTopState == 0 && $state == $tourState) {
                $data['is_top'] = Top::topRecommended;
                $data['update_time'] = date("Y-m-d H:i:s", time());
                M('tour')->where($where)->save($data);

                $userInfo = $this->getUserInfo($userId);

                if ($this->getTransactionMessageType($userInfo)) {
                    $toUser = $userInfo['weixinmp_openid'];
                    $templateId = Utils::productCheckResultTemplateId();
                    $content = "您好, 您的产品: 10" . $tourInfo['id'] . $tourInfo['name'] . " 已设为置顶推广";
                    $type = "产品置顶";
                    $this->send($toUser, $templateId, $content, $type);
                }

                $data['status'] = 1;
                $this->ajaxReturn($data);
            } else if ($isTopState == 1) {
                $data['is_top'] = Top::cancelTopRecommended;
                $data['update_time'] = date("Y-m-d H:i:s", time());
                M('tour')->where($where)->save($data);

                $userInfo = $this->getUserInfo($userId);

                if ($this->getTransactionMessageType($userInfo)) {
                    $toUser = $userInfo['weixinmp_openid'];
                    $templateId = Utils::productCheckResultTemplateId();
                    $content = "您好, 您的产品: 10" . $tourInfo['id'] . $tourInfo['name'] . " 已被取消置顶推广";
                    $type = "产品置顶";
                    $this->send($toUser, $templateId, $content, $type);
                }

                $data['status'] = 1;
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

        }
    }


    /**
     * 特价操作
     */
    public function setPromotion()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            $tourInfo = M('tour')->where($where)->field('id,name,promotion,user_id,state')->find();
            $userId = $tourInfo['user_id'];
            $isPromotion = $tourInfo['promotion'];
            $state = $tourInfo['state'];

            $tourState = Top::ProductStateIsSale;
            if ($isPromotion == 0 && $state == $tourState) {
                $data['promotion'] = Top::IsPromotion;
                $data['update_time'] = date("Y-m-d H:i:s", time());
                $result = M('tour')->where($where)->save($data);

                $userInfo = $this->getUserInfo($userId);

                if ($this->getTransactionMessageType($userInfo)) {
                    $toUser = $userInfo['weixinmp_openid'];
                    $templateId = Utils::productCheckResultTemplateId();
                    $content = "您好, 您的产品: 10" . $tourInfo['id'] . $tourInfo['name'] . " 已设为特价推广";
                    $type = "特价";
                    $this->send($toUser, $templateId, $content, $type);
                }

                if ($result) {
                    $data['status'] = 1;
                    $this->ajaxReturn($data);
                }
            } else if ($isPromotion == 1) {
                $data['promotion'] = Top::NotPromotion;
                $data['update_time'] = date("Y-m-d H:i:s", time());
                $result = M('tour')->where($where)->save($data);

                $userInfo = $this->getUserInfo($userId);

                if ($this->getTransactionMessageType($userInfo)) {
                    $toUser = $userInfo['weixinmp_openid'];
                    $templateId = Utils::productCheckResultTemplateId();
                    $content = "您好, 您的产品: 10" . $tourInfo['id'] . $tourInfo['name'] . " 已被取消特价推广";
                    $type = "特价";
                    $this->send($toUser, $templateId, $content, $type);
                }

                if ($result) {
                    $data['status'] = 1;
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

        }
    }


    /**
     * 外部订单设置
     */
    public function setOutOrder()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            $tourInfo = M('tour')->where($where)->field('id,provider_type,state')->find();
            $providerType = $tourInfo['provider_type'];
            $state = $tourInfo['state'];

            $tourState = Top::ProductStateIsSale;
            if ($providerType == 0 && $state == $tourState) {
                $data['provider_type'] = Top::IsOutOrder;
                $result = M('tour')->where($where)->save($data);
                if ($result) {
                    $data['status'] = 1;
                    $this->ajaxReturn($data);
                }
            } else if ($providerType == 1 && $state == $tourState) {
                $data['provider_type'] = Top::NotOutOrder;
                $result = M('tour')->where($where)->save($data);

                if ($result) {
                    $data['status'] = 1;
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

        }
    }


    /**
     * 产品详情
     */
    public function details()
    {
        $Provider = new \Model\ProviderModel();
        $this->provider_info = $Provider->checkAudit(I('aid', 0, 'int'));

        $this->din1 = '1';
        $this->din2 = '2';
        $this->din3 = '3';
        $this->display();
    }


    /**
     * 跑马灯设置
     */
    public function marquee()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $id = I('id');
            $where['id'] = $id;
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            $tourInfo = M('tour')->where($where)->field("id,name,user_id")->find();
            $userId = $tourInfo['user_id'];

            $data['marquee_start_time'] = I('marquee_start_time');
            $data['marquee_end_time'] = I('marquee_end_time');
            $data['is_marquee'] = I('is_marquee');
            $result = M('tour')->where($where)->save($data);

            if ($result) {
                $userInfo = $this->getUserInfo($userId);

                if ($this->getTransactionMessageType($userInfo)) {
                    if ($data['is_marquee'] == 1) {
                        $content = "您好, 您的产品: 10" . $tourInfo['id'] . $tourInfo['name'] . " 已设为跑马灯推广";
                    } else if ($data['is_marquee'] == 0) {
                        $content = "您好, 您的产品: 10" . $tourInfo['id'] . $tourInfo['name'] . " 已取消跑马灯推广";
                    }

                    $toUser = $userInfo['weixinmp_openid'];
                    $templateId = Utils::productCheckResultTemplateId();
                    $type = "跑马灯";
                    $this->send($toUser, $templateId, $content, $type);
                }

                $data['status'] = 1;
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }
        }
    }

    //查看顾问对供应商的意见反馈[平台/运营商]
    public function supplier_feedback(){
         $name = trim(I('names'));
        $operatorId = session('operator_id');
        $state = Top::StateDeleted;
        $roleId = session('role_id');

        $this->operatorData = C('SHOW_OPERATOR_DATA');

        if (strpos($this->operatorData, $roleId) !== false) {
            $this->operatorList = M('operator')->where('id != 2')->field('id,display_name')->select();
            $this->oid = !empty(I('get.oid')) ? I('get.oid') : 0;
            $operatorId = $this->oid;

            if ($this->oid == 0) {
                $operatorId = implode(',', array_column($this->operatorList, 'id'));
            }
        }

        if ($name) {
            $where = "operator_id in($operatorId) && comment_type = 1 && (cover_commnet_name like '%%$name%%' )";
        } else {
            $where = "operator_id in($operatorId) && comment_type = 1 ";
        }


        $list = Utils::pages('feedback', $where, C('PAGE_SET'), $order = " id desc ");
       
        $this->assign('name', $name);
        $this->info = $list['info'];
        $this->page = $list['page'];
        $this->oper = M('operator')->field('id,name')->find(session('entity_id'));
        $this->display();
    }
    //查看顾问对供应商的意见反馈[供应商]
    public function supplier_feedback_g(){
         $name = trim(I('names'));
        $provider_id = session('provider_id');
        if ($name) {
            $where = "cover_commnet_id = '{$provider_id}'  && comment_type = 1 && (cover_commnet_name like '%%$name%%' )";
        } else {
            $where = "cover_commnet_id = '{$provider_id}' && comment_type = 1 ";
        }


        $list = Utils::pages('feedback', $where, C('PAGE_SET'), $order = " id desc ");
       
        $this->assign('name', $name);
        $this->info = $list['info'];
        $this->page = $list['page'];
        $this->oper = M('operator')->field('id,name')->find(session('entity_id'));
        $this->display();
    }
////ajax设置跑马灯有效时间
//    public function showMarqueeInfo()
//    {
//        if (IS_POST && IS_AJAX) {
//            $where['id'] = I('id');
//            $info = M('tour')->where($where)->find();
//
//            if ($info['marquee_start_time'] == '0000-00-00 00:00:00') {
//                unset($info['marquee_start_time']);
//            }
//
//            if ($info['marquee_end_time'] == '0000-00-00 00:00:00') {
//                unset($info['marquee_end_time']);
//            }
//
//            if ($info) {
//                $data['status'] = 1;
//                $data['marquee_start_time'] = isset($info['marquee_start_time']) ? substr($info['marquee_start_time'], 0, 10) : '';
//                $data['marquee_end_time'] = isset($info['marquee_end_time']) ? substr($info['marquee_end_time'], 0, 10) : '';
//                $data['is_marquee'] = $info['is_marquee'];
//                $this->ajaxReturn($data);
//            }
//        }
//    }


    public function getUserInfo($userId)
    {
        $userInfo = M('user')->where("id = '{$userId}'")->field("id,notify_msg_types,weixinmp_openid")->find();
        return $userInfo;
    }


    public function getTransactionMessageType($userInfo)
    {
        $notifyMsgTypes = explode(",", $userInfo['notify_msg_types']);
        array_shift($notifyMsgTypes);
        array_pop($notifyMsgTypes);
        $transactionMessage = $notifyMsgTypes[0];
        return $transactionMessage;
    }


    public function send($toUser, $templateId, $content, $type, $remark)
    {
        $template = array(
            'touser' => $toUser,
            'template_id' => $templateId,

            'data' => array(
                'first' => array('value' => urlencode($content), 'color' => "#000"),
                'keyword1' => array('value' => urlencode($type), 'color' => "#000"),
                'keyword2' => array('value' => urlencode(date("Y-m-d H:i:s", time())), 'color' => '#000'),
                'remark' => array('value' => urlencode($remark), 'color' => '#000'),
            )
        );

        $this->send_tpl($template);
    }

}